﻿using System;
using System.Collections.Generic;
using System.Linq;
using PmSadis.WebFormsUi.ExpandedControls;
using PmSadis.Repositories.Abstract;
using PmSadis.CsExtantions;
using DevExpress.Web.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxGridLookup;

namespace PmSadis.WebFormsUi.Operator
{
    public partial class Elements : System.Web.UI.Page
    {
        private const string __operExpandedElementId = "oper-expanded-element-id";
        private IListRepository<Models.Element> _repo = new Repositories.ElementRepository();
        private IListRepository<Models.Unit> _repoUnits = new Repositories.UnitRepository();
        private IListRepository<Models.Work> _repoWorks = new Repositories.WorkRepository();
        private IListRepository<Models.ElementWork> _repoElementWorks = new Repositories.ElementWorkRepository();
        
        protected void gvElements_Init(object sender, EventArgs e)
        {
            gvElements.ForceDataRowType(typeof(Models.Element));
            gvElements.SetDefaultSettings();
        }

        public IQueryable<PmSadis.Models.Element> GetAll()
        {
            var result = _repo.All.OrderBy(x => x.Name);
            return result;
        }
        public void InsertElement(string name, PmSadis.Models.Enums.ElementType elementType, PmSadis.Models.Enums.ObjectType objectType, int unitId)
        {
            var element = new PmSadis.Models.Element {
                ElementId=0,
                Name=name,
                ElementType=elementType,
                ObjectType=objectType,
                UnitId=unitId
            };
            _repo.Edit(element);
        }
        public void UpdateElement(int elementId, DateTime dateCreate, string name, PmSadis.Models.Enums.ElementType elementType, PmSadis.Models.Enums.ObjectType objectType, int unitId)
        {
            var element = new PmSadis.Models.Element
            {
                ElementId = elementId,
                DateCreate=dateCreate,
                Name = name,
                ElementType = elementType,
                ObjectType=objectType,
                UnitId=unitId
            };
            _repo.Edit(element);
        }
        public void DeleteElement(int elementId)
        {
            _repo.Delete(elementId);
        }

        protected void gvElements_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["UnitId"] as GridViewDataColumn, "lucUnits") as ASPxGridLookup;
            var unitId = lookup.Value;
            e.NewValues["UnitId"] = Convert.ToInt32(unitId);
        }
        protected void gvElements_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var dateCreate = grid.GetRowValues(grid.EditingRowVisibleIndex, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["UnitId"] as GridViewDataColumn, "lucUnits") as ASPxGridLookup;
            var unitId = lookup.Value;
            e.NewValues["UnitId"] = Convert.ToInt32(unitId);
        }

        protected void lucUnits_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var materialtId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(materialtId);
            }
        }

        public IQueryable<PmSadis.Models.Unit> Units()
        {
            return _repoUnits.All.OrderBy(x => x.Name);
        }

        /*Работы на элементе*/
        public IQueryable<Models.ElementWork> ElementWorks(int elementId)
        {
            var results = _repo.All.FirstOrDefault(x => x.ElementId == elementId).ElementWorks
                .OrderBy(x => x.Work.Name)
                .AsQueryable();
            return results;
        }
        public void InsertElementWork(int elementId, string worksId)
        {
            var ids = worksId.Split(';').ToList();
            if (ids.Count == 0) return;

            foreach(var id in ids)
            {
                var elementWork = new Models.ElementWork
                {
                    ElementWorkId = 0,
                    WorkId = Convert.ToInt32(id),
                    ElementId = elementId
                };
                _repoElementWorks.Edit(elementWork);
            }
        }
        public void DeleteElementWork(int elementWorkId)
        {
            _repoElementWorks.Delete(elementWorkId);
        }

        protected void gvElementWorks_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.ElementWork));
            grid.SetDefaultSettings();
        }
        protected void gvElementWorks_BeforePerformDataSelect(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            var elementId = grid.GetMasterRowKeyValue();
            Session[__operExpandedElementId] = elementId;
        }
        protected void lucWorks_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var workId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(workId);
            }
        }
        protected void gvElementWorks_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["WorkId"] as GridViewDataColumn, "lucWorks") as ASPxGridLookup;
            var strWorksId = string.Empty;
            lookup.GridView.GetSelectedFieldValues("WorkId").ToList().ForEach(x => {
                strWorksId += string.Format(";{0}", x);
            });

            dsElementWorks.InsertParameters["WorksId"].DefaultValue=strWorksId.Substring(1);

            e.NewValues["ElementId"] = Session[__operExpandedElementId];
        }

        public IQueryable<Models.Work> Works(int elementId)
        {
            var existWorksId = ElementWorks(elementId).Select(x => x.WorkId);
            return _repoWorks.All.Where(x=>!existWorksId.Contains(x.WorkId)).OrderBy(x => x.Name);
        }
    }
}